# -*- encoding: utf-8 -*-
##############################################################################
#
##############################################################################

from odoo import fields, models, api, _
from odoo.exceptions import UserError, AccessError
from odoo.exceptions import ValidationError
from operator import itemgetter


class res_partner(models.Model):
    _inherit = 'res.partner'

    @api.multi
    def _out_credit_debit_get(self):
        tables, where_clause, where_params = self.env['account.move.line']._query_get()
        where_params = [tuple(self.ids)] + where_params
        if where_clause:
            where_clause = 'AND ' + where_clause
        self._cr.execute("""SELECT account_move_line.partner_id, act.type, SUM(account_move_line.amount_residual)
                          FROM account_move_line
                          LEFT JOIN account_account a ON (account_move_line.account_id=a.id)
                          LEFT JOIN account_account_type act ON (a.user_type_id=act.id)
                          WHERE act.type IN ('receivable','payable')
                          AND account_move_line.partner_id IN %s
                          AND account_move_line.reconciled IS FALSE
                          AND account_move_line.date_maturity < now()
                          """ + where_clause + """
                          GROUP BY account_move_line.partner_id, act.type
                          """, where_params)
        for pid, type, val in self._cr.fetchall():
            partner = self.browse(pid)
            if type == 'receivable':
                partner.date_out_credit = val

    @api.model
    def _out_credit_search(self, operator, operand):
        return self._asset_out_credit_search('receivable', operator, operand)

    @api.multi
    def _asset_out_credit_search(self, account_type, operator, operand):
        if operator not in ('<', '=', '>', '>=', '<='):
            return []
        if type(operand) not in (float, int):
            return []
        sign = 1
        if account_type == 'payable':
            sign = -1
        res = self._cr.execute('''
                SELECT partner.id
                FROM res_partner partner
                LEFT JOIN account_move_line aml ON aml.partner_id = partner.id
                RIGHT JOIN account_account acc ON aml.account_id = acc.id
                WHERE acc.internal_type = %s
                  AND NOT acc.deprecated
                  AND account_move_line.date_maturity < now()
                GROUP BY partner.id
                HAVING %s * COALESCE(SUM(aml.amount_residual), 0) ''' + operator + ''' %s''',
                               (account_type, sign, operand))
        res = self._cr.fetchall()
        if not res:
            return [('id', '=', '0')]
        return [('id', 'in', map(itemgetter(0), res))]

    line_of_credit = fields.Monetary(u'逾期额度', default=0, copy=False)
    credit_limit_symbol = fields.Char(string=u'货币符号', related='currency_id.symbol')
    switch_of_credit = fields.Boolean(u'启用逾期应收限制', default=False)
    date_out_credit = fields.Monetary(compute='_out_credit_debit_get', search=_out_credit_search, string=u'逾期应收')

    user_edit_credit_limit = fields.Boolean(string=u"修改额度权限", compute="_get_user_edit_credit_limit")
    # allow_date = fields.Date(string=u"放宽期限")
    red_line_of_credit = fields.Boolean(u'启用信用额度限制', default=False)

    @api.one
    def _get_user_edit_credit_limit(self):
        self.user_edit_credit_limit = self.env['res.users'].has_group(
            'sale_line_of_credit.group_sale_order_specially_confirm')
